package com.handpay.zztong.hp.db.ormlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.model.component.ComponentItemBean;
import com.handpay.zztong.hp.main.model.component.ComponentMappingItemBean;
import com.handpay.zztong.hp.main.model.component.ComponentRelationItemBean;
import com.handpay.zztong.hp.notification.model.NoticeBody;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

/**
 * @author sxshi on 2017/4/6.
 *         email:emotiona_xiaoshi@126.com
 *         describe:数据库操作
 */

public class DataBaseHelper extends OrmLiteSqliteOpenHelper {
    // 数据库名称
    private static final String DATABASE_NAME = "handpay.db";
    // 数据库版本
    private static int DB_VERSION = 6;
    private static DataBaseHelper instance;

    private DataBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DB_VERSION);
    }

    public static synchronized DataBaseHelper getDBHelper(Context context) {
        context = context.getApplicationContext();
        if (instance == null) {
            synchronized (DataBaseHelper.class) {
                if (instance == null) {
                    instance = new DataBaseHelper(context);
                }
            }
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            HPLog.d(HPLog.SSX_TAG, "DataBaseHelper-onCreate");
            TableUtils.createTable(connectionSource, NoticeBody.class);
            TableUtils.createTable(connectionSource, ComponentItemBean.class);
            TableUtils.createTable(connectionSource, ComponentMappingItemBean.class);
            TableUtils.createTable(connectionSource, ComponentRelationItemBean.class);
        } catch (SQLException e) {
            HPLog.e(HPLog.SSX_TAG, "Can't not create database " + e);
            throw new RuntimeException(e);
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            HPLog.d(HPLog.SSX_TAG, "DataBaseHelper-onUpgrade");
            TableUtils.dropTable(connectionSource, NoticeBody.class, true);
            TableUtils.dropTable(connectionSource, ComponentItemBean.class, true);
            TableUtils.dropTable(connectionSource, ComponentMappingItemBean.class, true);
            TableUtils.dropTable(connectionSource, ComponentRelationItemBean.class, true);
            onCreate(database, connectionSource);
        } catch (SQLException e) {
            HPLog.e(HPLog.SSX_TAG, "Can't create drop database" + e);
            throw new RuntimeException(e);
        }
    }
}
